package com.shioirikukuri.controller;

import com.shioirikukuri.common.until.PictureUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api")
public class UploadController {
	/**
	 * 处理图片上传请求，使用 PictureUtil 上传至七牛云
	 *
	 * @param file
	 * @return 七牛云图片的URL
	 */
	@PostMapping("/upload")
	public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return ResponseEntity.badRequest().body("Failed to upload. File is empty.");
		}

		try {
			// 将 MultipartFile 写入临时文件（因为 PictureUtil 目前接受的是路径）
			File tempFile = File.createTempFile("upload-", ".tmp");
			file.transferTo(tempFile);

			// 使用工具类上传到七牛云
			String imageUrl = PictureUtil.uploadPicture(tempFile.getAbsolutePath());

			// 删除临时文件
			tempFile.delete();

			if (imageUrl == null || imageUrl.isEmpty()) {
				return ResponseEntity.status(500).body("Upload failed, image URL is null.");
			}

			// 返回七牛云图片的URL
			return ResponseEntity.ok(imageUrl);

		} catch (IOException e) {
			return ResponseEntity.status(500).body("Could not upload the file: " + file.getOriginalFilename() + " => " + e.getMessage());
		}
	}
}
